/**
 * @param {string} url
 * @returns {Object}
 */
export function getQueryObject(url) {
  url = url == null ? window.location.href : url;
  const search = url.substring(url.lastIndexOf("?") + 1);
  const obj = {};
  const reg = /([^?&=]+)=([^?&=]*)/g;
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1);
    let val = decodeURIComponent($2);
    val = String(val);
    obj[name] = val;
    return rs;
  });
  return obj;
}

/**
 * @param {string} input value
 * @returns {number} output value
 */
export function byteLength(str) {
  // returns the byte length of an utf8 string
  let s = str.length;
  for (var i = str.length - 1; i >= 0; i--) {
    const code = str.charCodeAt(i);
    if (code > 0x7f && code <= 0x7ff) s++;
    else if (code > 0x7ff && code <= 0xffff) s += 2;
    if (code >= 0xdc00 && code <= 0xdfff) i--;
  }
  return s;
}

/**
 * @param {Array} actual
 * @returns {Array}
 */
export function cleanArray(actual) {
  const newArray = [];
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i]);
    }
  }
  return newArray;
}

/**
 * @param {Object} json
 * @returns {Array}
 */
export function param(json) {
  if (!json) return "";
  return cleanArray(
    Object.keys(json).map(key => {
      if (json[key] === undefined) return "";
      return encodeURIComponent(key) + "=" + encodeURIComponent(json[key]);
    })
  ).join("&");
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = url.split("?")[1];
  if (!search) {
    return {};
  }
  return JSON.parse(
    '{"' +
      decodeURIComponent(search)
        .replace(/"/g, '\\"')
        .replace(/&/g, '","')
        .replace(/=/g, '":"')
        .replace(/\+/g, " ") +
      '"}'
  );
}

/**
 * @param {string} val
 * @returns {string}
 */
export function html2Text(val) {
  const div = document.createElement("div");
  div.innerHTML = val;
  return div.textContent || div.innerText;
}

/**
 * Merges two objects, giving the last one precedence
 * @param {Object} target
 * @param {(Object|Array)} source
 * @returns {Object}
 */
export function objectMerge(target, source) {
  if (typeof target !== "object") {
    target = {};
  }
  if (Array.isArray(source)) {
    return source.slice();
  }
  Object.keys(source).forEach(property => {
    const sourceProperty = source[property];
    if (typeof sourceProperty === "object") {
      target[property] = objectMerge(target[property], sourceProperty);
    } else {
      target[property] = sourceProperty;
    }
  });
  return target;
}

/**
 * @param {HTMLElement} element
 * @param {string} className
 */
export function toggleClass(element, className) {
  if (!element || !className) {
    return;
  }
  let classString = element.className;
  const nameIndex = classString.indexOf(className);
  if (nameIndex === -1) {
    classString += "" + className;
  } else {
    classString =
      classString.substr(0, nameIndex) +
      classString.substr(nameIndex + className.length);
  }
  element.className = classString;
}

/**
 * @param {string} type
 * @returns {Date}
 */
export function getTime(type) {
  if (type === "start") {
    return new Date().getTime() - 3600 * 1000 * 24 * 90;
  } else {
    return new Date(new Date().toDateString());
  }
}

/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result;

  const later = function() {
    const last = +new Date() - timestamp;
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last);
    } else {
      timeout = null;
      if (!immediate) {
        result = func.apply(context, args);
        if (!timeout) context = args = null;
      }
    }
  };

  return function(...args) {
    context = this;
    timestamp = +new Date();
    const callNow = immediate && !timeout;
    if (!timeout) timeout = setTimeout(later, wait);
    if (callNow) {
      result = func.apply(context, args);
      context = args = null;
    }

    return result;
  };
}

/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
export function deepClone(source) {
  if (!source && typeof source !== "object") {
    throw new Error("error arguments", "deepClone");
  }
  const targetObj = source.constructor === Array ? [] : {};
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === "object") {
      targetObj[keys] = deepClone(source[keys]);
    } else {
      targetObj[keys] = source[keys];
    }
  });
  return targetObj;
}

/**
 * @param {Array} arr
 * @returns {Array}
 */
export function uniqueArr(arr) {
  return Array.from(new Set(arr));
}

/**
 * @returns {string}
 */
export function createUniqueString() {
  const timestamp = +new Date() + "";
  const randomNum = parseInt((1 + Math.random()) * 65536) + "";
  return (+(randomNum + timestamp)).toString(32);
}

/**
 * Check if an element has a class
 * @param {HTMLElement} elm
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass(ele, cls) {
  return !!ele.className.match(new RegExp("(\\s|^)" + cls + "(\\s|$)"));
}

/**
 * Add class to element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function addClass(ele, cls) {
  if (!hasClass(ele, cls)) ele.className += " " + cls;
}

/**
 * Remove class from element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function removeClass(ele, cls) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp("(\\s|^)" + cls + "(\\s|$)");
    ele.className = ele.className.replace(reg, " ");
  }
}

/**
 * @param {Object} obj
 * @param {Function} fn
 */
export function checkBe(obj) {
  if (!(typeof obj === "object")) {
    return;
  }
  for (var key in obj) {
    if (
      Object.prototype.hasOwnProperty.call(obj, key) &&
      (obj[key] === undefined || obj[key] === "")
    ) {
      delete obj[key];
    }
  }
  return obj;
}

/**
 * @param {Object} obj
 * @param {Function} fn
 */
export function mergeObjOfValue(tarObj, obj) {
  for (var key in obj) {
    if (Object.prototype.hasOwnProperty.call(tarObj, key) === true) {
      tarObj[key] = obj[key];
    }
  }
}

export function mergeArray(targetArray, array, key) {
  const resultArray = [];
  const allArray = targetArray.concat(array);
  const allKey = new Set(allArray.map(item => item[key]));
  for (const item of allKey) {
    const commonKeyArray = allArray.filter(e => e[key] === item);
    if (commonKeyArray.length > 1) {
      for (var prop in commonKeyArray[1]) {
        commonKeyArray[0][prop] = commonKeyArray[1][prop];
      }
      resultArray.push(commonKeyArray[0]);
    } else {
      resultArray.push(...commonKeyArray);
    }
  }
  return resultArray;
}

export function changeOption(data, props) {
  for (let i = 0; i < data.length; i++) {
    for (var prop in props) {
      data[i][prop] = data[i][props[prop]];
      delete data[i][props[prop]];
    }
    if (data[i].children) {
      if (data[i].children.length < 1) {
        data[i].children = undefined;
      } else {
        changeOption(data[i].children, props);
      }
    }
  }
  return data;
}

export function assignmentObj(targetObj, obj) {
  if (!(typeof obj === "object")) {
    return;
  }
  for (var key in targetObj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      targetObj[key] = obj[key];
    }
  }
  return targetObj;
}

export function assignmentObjforList(targetObj, listTypeInfo, details) {
  if (listTypeInfo.length === 0) {
    return targetObj;
  }
  for (var key in listTypeInfo) {
    if (Object.prototype.hasOwnProperty.call(targetObj, key)) {
      targetObj[key] = details[key];
    }
  }
  return targetObj;
}

export function getObjectAllKey(data, key, children = "children") {
  const array = [];
  for (let i = 0; i < data.length; i++) {
    if (data[i][children] && data[i][children].length) {
      array.push(...getObjectAllKey(data[i][children], key, children));
    } else {
      array.push(data[i][key]);
    }
  }
  return array;
}

export function checkArrayKey(arrStr, arrObj, key) {
  let exist = false;
  let copyArrObj = [...arrObj];
  for (let i = 0; i < arrStr.length; i++) {
    const isExistObj = copyArrObj.filter(
      item => item[key].replace(/\//, "") === arrStr[i]
    );
    if (isExistObj.length) {
      if (i < arrStr.length) {
        copyArrObj = isExistObj[0].children;
      }
      exist = true;
    } else {
      exist = false;
    }
  }
  return exist;
}
/* eslint-disable */
export function filterStr (str) {
  return str.replace(/[\-\_\,\!\|\~\`\(\)\#\$\%\^\&\*\{\}\:\;\"\L\<\>\?]/g, '');
}

export function downloadFile (content, filename) {
  var eleLink = document.createElement('a')
  eleLink.download = filename
  eleLink.style.display = 'none'
  var blob = new Blob([content])
  eleLink.href = URL.createObjectURL(blob)
  document.body.appendChild(eleLink)
  eleLink.click()
  document.body.removeChild(eleLink)
};

export function getFathersById (id, data, prop = 'id') {
  var arrRes = []
  const rev = (data, nodeId) => {
    for (var i = 0, length = data.length; i < length; i++) {
      const node = data[i]
      if (node[prop] === nodeId) {
        arrRes.unshift(node[prop])
        return true
      } else {
        if (node.children && node.children.length) {
          if (rev(node.children, nodeId)) {
            arrRes.unshift(node[prop])
            return true
          }
        }
      }
    }
    return false
  }
  rev(data, id)
  return arrRes
}


